<template>
   <ptitle title="小画家"/>
   <textarea v-model="prompt" cols="50" rows="3" placeholder='请录入图片需求'></textarea><br/>
   生成数量:<input type="number" v-model="qty"/>
   <button @click="send">生成图片</button><br/>
   <span v-if="taskId!=''">任务请求成功:{{taskId}}</span>
   <load v-if="isLoading"/>
   <hr>
   <img height="200px" v-for="u in urls" v-bind:key="u" v-bind:src="u"/>
</template>
<script>
   import axios from '../axios/index-ai.js'
   import load from '../components-ai/Loading.vue'
   import ptitle from '../components-ai/PageTitle.vue'
   import {useInfoStore} from "../store/InfoStore"
   export default{
      components:{load,ptitle}
      ,data(){
        return {
            prompt:''
            ,qty:1
            ,taskId:''
            ,isLoading:false
            ,timer:null
            ,urls:[]
        }
      }
      ,methods:{
        queryResult:function(){
            const store=useInfoStore();
            console.log("查询结果")
            axios.get("/aa/api/v1/tasks/"+this.taskId)
            .then(d=>{
              if(d.data.output.task_status=="FAILED"){
                 window.clearInterval(this.timer);
                 alert("任务失败,请后续尝试");
                 this.isLoading=false;
                 return;
              }
               if(d.data.output.task_status=="SUCCEEDED"){
                  let results=d.data.output.results;
                  for(let i=0;i<results.length;i++){
                    this.urls.push(results[i].url)
                  }
                  console.log(this.timer,"停止定时器")
                  window.clearInterval(this.timer);
                  this.isLoading=false;
                  store.addImg(results.length);
               }
           })

        }
        ,send:function(){
           var that=this;
           axios.post("/aa/api/v1/services/aigc/text2image/image-synthesis"
           ,{
                "model": "wanx2.1-t2i-turbo",
                "input": {
                    "prompt": this.prompt
                },
                "parameters": {
                    "size": "1024*1024",
                    "n": this.qty
                }
           }
             ,{
                headers:{
                    'X-DashScope-Async':'enable'
                }
             }
           )
           .then(function(d){
                //应该会接收到一张小票
                if(d.data.output){
                   that.taskId= d.data.output.task_id;
                   that.isLoading=true;
                   that.timer=window.setInterval(that.queryResult,10000)
                }
                else
                   alert("生成任务请求未成功:"+d.data.message)
            }) 

        }
      }
   }
</script>
<style scoped>
</style>